{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-01-08T07:15:56.176283Z",
     "start_time": "2025-01-08T07:15:55.403990Z"
    }
   },
   "source": "import pandas as pd",
   "outputs": [],
   "execution_count": 1
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 2 Series",
   "id": "5050e13107dd6d50"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:15:56.181833Z",
     "start_time": "2025-01-08T07:15:56.177285Z"
    }
   },
   "cell_type": "code",
   "source": [
    "ser_obj = pd.Series(range(10, 20))  #默认索引是0-9\n",
    "print(ser_obj)  # #打印输出会带有类型"
   ],
   "id": "b954e6984ead3dd2",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    10\n",
      "1    11\n",
      "2    12\n",
      "3    13\n",
      "4    14\n",
      "5    15\n",
      "6    16\n",
      "7    17\n",
      "8    18\n",
      "9    19\n",
      "dtype: int64\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:15:56.188514Z",
     "start_time": "2025-01-08T07:15:56.182836Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 获取数据\n",
    "print(ser_obj.values)  #values实际是ndarray类型\n",
    "print(type(ser_obj.values))  # <class 'nump.ndarray'>\n",
    "\n",
    "# 获取索引\n",
    "print(ser_obj.index)  #index实际是RangeIndex类型\n",
    "# RangeIndex(start=0, stop=10, step=1)\n",
    "print(type(ser_obj.index))\n",
    "# <class 'pandas.core.indexes.range.RangeIndex'>\n",
    "\n",
    "print(ser_obj.dtype)  # 数据类型：int64"
   ],
   "id": "6fa5b63182194fdf",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[10 11 12 13 14 15 16 17 18 19]\n",
      "<class 'numpy.ndarray'>\n",
      "RangeIndex(start=0, stop=10, step=1)\n",
      "<class 'pandas.core.indexes.range.RangeIndex'>\n",
      "int64\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:15:56.195496Z",
     "start_time": "2025-01-08T07:15:56.190520Z"
    }
   },
   "cell_type": "code",
   "source": [
    "print(ser_obj[0])\n",
    "print(ser_obj[9])\n",
    "# print(ser_obj[10]) # 访问不存在的索引下标会报keyerror "
   ],
   "id": "ac8d78203a6f4366",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n",
      "19\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:15:56.204538Z",
     "start_time": "2025-01-08T07:15:56.196502Z"
    }
   },
   "cell_type": "code",
   "source": [
    "print(ser_obj * 2)  # 元素级乘法 广播机制\n",
    "print(ser_obj > 15)  # 元素级比较 广播机制,返回一个bool系列"
   ],
   "id": "987451fdce7cbc6c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    20\n",
      "1    22\n",
      "2    24\n",
      "3    26\n",
      "4    28\n",
      "5    30\n",
      "6    32\n",
      "7    34\n",
      "8    36\n",
      "9    38\n",
      "dtype: int64\n",
      "0    False\n",
      "1    False\n",
      "2    False\n",
      "3    False\n",
      "4    False\n",
      "5    False\n",
      "6     True\n",
      "7     True\n",
      "8     True\n",
      "9     True\n",
      "dtype: bool\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:15:56.213873Z",
     "start_time": "2025-01-08T07:15:56.205545Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#字典变为series，索引是字典的key，value是字典的value，感受非默认索引\n",
    "\n",
    "year_data = {2001: 17.8, 2005: 20.1, 2003: 16.5}\n",
    "ser_obj = pd.Series(year_data)\n",
    "print(ser_obj)\n",
    "# 2001    17.8\n",
    "# 2005    20.1\n",
    "# 2003    16.5\n",
    "# dtype: float64\n",
    "\n",
    "print(\"-\" * 50)\n",
    "\n",
    "print(ser_obj.index)  # 索引是字典的key\n",
    "# Index([2001, 2005, 2003], dtype='int64')\n",
    "\n",
    "print(\"-\" * 50)\n",
    "\n",
    "print(ser_obj.values)  # 值是字典的value\n",
    "# [17.8 20.1 16.5]\n",
    "\n",
    "print(\"-\" * 50)\n",
    "\n",
    "print(ser_obj[2001])"
   ],
   "id": "21c43d3ec850973a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2001    17.8\n",
      "2005    20.1\n",
      "2003    16.5\n",
      "dtype: float64\n",
      "--------------------------------------------------\n",
      "Index([2001, 2005, 2003], dtype='int64')\n",
      "--------------------------------------------------\n",
      "[17.8 20.1 16.5]\n",
      "--------------------------------------------------\n",
      "17.8\n"
     ]
    }
   ],
   "execution_count": 6
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:15:56.220046Z",
     "start_time": "2025-01-08T07:15:56.214880Z"
    }
   },
   "cell_type": "code",
   "source": [
    "print(ser_obj.name)  # Series名字 ，找不到就返回None\n",
    "print(ser_obj.index.name)  # 索引名字，找不到就返回None\n",
    "print(\"-\" * 50)\n",
    "\n",
    "ser_obj.name = \"temp\"\n",
    "ser_obj.index.name = \"year\"\n",
    "print(ser_obj)\n",
    "print(\"-\" * 50)\n",
    "print(ser_obj.head())  # head默认显示前5行"
   ],
   "id": "4a3b34125e930327",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n",
      "None\n",
      "--------------------------------------------------\n",
      "year\n",
      "2001    17.8\n",
      "2005    20.1\n",
      "2003    16.5\n",
      "Name: temp, dtype: float64\n",
      "--------------------------------------------------\n",
      "year\n",
      "2001    17.8\n",
      "2005    20.1\n",
      "2003    16.5\n",
      "Name: temp, dtype: float64\n"
     ]
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 3 DataFrame",
   "id": "64609eb0fb742c76"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:15:56.228832Z",
     "start_time": "2025-01-08T07:15:56.222051Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "# 通过ndarray构建DataFrame\n",
    "t = pd.DataFrame(np.arange(12).reshape(3, 4))\n",
    "print(t)"
   ],
   "id": "f3c2fcda91aedd42",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   0  1   2   3\n",
      "0  0  1   2   3\n",
      "1  4  5   6   7\n",
      "2  8  9  10  11\n"
     ]
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:15:56.236889Z",
     "start_time": "2025-01-08T07:15:56.229837Z"
    }
   },
   "cell_type": "code",
   "source": [
    "arr = np.random.rand(5, 4)\n",
    "print(arr)\n",
    "print(\"-\" * 50)\n",
    "\n",
    "df_obj = pd.DataFrame(arr)\n",
    "print(df_obj)"
   ],
   "id": "e5e498fbf5a8aa45",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0.23150583 0.04567454 0.59148981 0.68890364]\n",
      " [0.51633413 0.02919214 0.15594552 0.33538612]\n",
      " [0.89158864 0.87323409 0.02090361 0.03585195]\n",
      " [0.08479361 0.44078647 0.66225312 0.56054844]\n",
      " [0.07632595 0.09458285 0.05922221 0.94651025]]\n",
      "--------------------------------------------------\n",
      "          0         1         2         3\n",
      "0  0.231506  0.045675  0.591490  0.688904\n",
      "1  0.516334  0.029192  0.155946  0.335386\n",
      "2  0.891589  0.873234  0.020904  0.035852\n",
      "3  0.084794  0.440786  0.662253  0.560548\n",
      "4  0.076326  0.094583  0.059222  0.946510\n"
     ]
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:16:13.671769Z",
     "start_time": "2025-01-08T07:16:13.665684Z"
    }
   },
   "cell_type": "code",
   "source": [
    "print(t.loc[0])  # 单独把某一行取出来,类型是series\n",
    "print(t.loc[1])\n",
    "print(t.loc[2])\n",
    "print(t.iloc[2])\n",
    "print(type(t.loc[0]))  # <class 'pandas.core.series.Series'>"
   ],
   "id": "5731f6a99b9abce7",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    0\n",
      "1    1\n",
      "2    2\n",
      "3    3\n",
      "Name: 0, dtype: int64\n",
      "0    4\n",
      "1    5\n",
      "2    6\n",
      "3    7\n",
      "Name: 1, dtype: int64\n",
      "0     8\n",
      "1     9\n",
      "2    10\n",
      "3    11\n",
      "Name: 2, dtype: int64\n",
      "0     8\n",
      "1     9\n",
      "2    10\n",
      "3    11\n",
      "Name: 2, dtype: int64\n",
      "<class 'pandas.core.series.Series'>\n"
     ]
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:17:54.082394Z",
     "start_time": "2025-01-08T07:17:54.074786Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 列表套字典，变df\n",
    "d2 = [{\"name\": \"xiaohong\", \"age\": 32, \"tel\": 10010},\n",
    "      {\"name\": \"xiaogang\", \"tel\": 10000},\n",
    "      {\"name\": \"xiaowang\", \"age\": 22}]\n",
    "df6 = pd.DataFrame(d2)\n",
    "print(df6)  # 缺失值会用NaN填充\n",
    "print(\"-\" * 50)\n",
    "print(type(df6.values))  # <class 'numpy.ndarray'>\n",
    "print(\"-\" * 50)\n",
    "print(df6.loc[0])\n",
    "print(\"-\" * 50)\n",
    "print(df6.loc[1])\n",
    "print(\"-\" * 50)\n",
    "print(df6[\"name\"])"
   ],
   "id": "47883ef8a3a1ea85",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       name   age      tel\n",
      "0  xiaohong  32.0  10010.0\n",
      "1  xiaogang   NaN  10000.0\n",
      "2  xiaowang  22.0      NaN\n",
      "--------------------------------------------------\n",
      "<class 'numpy.ndarray'>\n",
      "--------------------------------------------------\n",
      "name    xiaohong\n",
      "age         32.0\n",
      "tel      10010.0\n",
      "Name: 0, dtype: object\n",
      "--------------------------------------------------\n",
      "name    xiaogang\n",
      "age          NaN\n",
      "tel      10000.0\n",
      "Name: 1, dtype: object\n",
      "--------------------------------------------------\n",
      "0    xiaohong\n",
      "1    xiaogang\n",
      "2    xiaowang\n",
      "Name: name, dtype: object\n"
     ]
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T16:01:28.019262Z",
     "start_time": "2025-01-07T16:01:28.014501Z"
    }
   },
   "cell_type": "code",
   "source": [
    "ser_obj = pd.Series(1, index=list(range(10)), dtype=float)\n",
    "print(ser_obj)"
   ],
   "id": "939dc68f9043c469",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    1.0\n",
      "1    1.0\n",
      "2    1.0\n",
      "3    1.0\n",
      "4    1.0\n",
      "5    1.0\n",
      "6    1.0\n",
      "7    1.0\n",
      "8    1.0\n",
      "9    1.0\n",
      "dtype: float64\n"
     ]
    }
   ],
   "execution_count": 33
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T16:27:55.969514Z",
     "start_time": "2025-01-07T16:27:55.962431Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# df中不同列可以是不同的数据类型,同一列必须是一个数据类型\n",
    "\n",
    "# timestamp类型 \n",
    "# 日期时间类型，可以用pd.Timestamp()构造，可以用pd.to_datetime()转换为datetime类\n",
    "dict_data = {'A': 1,\n",
    "             'B': pd.Timestamp('20190926'),\n",
    "             'C': pd.Series(1, index=list(range(4)), dtype='float32'),\n",
    "             'D': np.array([1, 2, 3, 4], dtype='int32'),\n",
    "             'E': [\"Python\", \"Java\", \"C++\", \"C\"],\n",
    "             'F': 'wangdao'}\n",
    "df_obj = pd.DataFrame(dict_data)\n",
    "print(df_obj)"
   ],
   "id": "ceea00b2f979cce8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A          B    C  D       E        F\n",
      "0  1 2019-09-26  1.0  1  Python  wangdao\n",
      "1  1 2019-09-26  1.0  2    Java  wangdao\n",
      "2  1 2019-09-26  1.0  3     C++  wangdao\n",
      "3  1 2019-09-26  1.0  4       C  wangdao\n"
     ]
    }
   ],
   "execution_count": 61
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T16:58:07.736694Z",
     "start_time": "2025-01-07T16:58:07.728174Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 取数据\n",
    "print(df_obj)\n",
    "print(\"-\" * 50)\n",
    "print(type(df_obj))\n",
    "print(\"-\" * 50)\n",
    "\n",
    "print(df_obj['B']) # 使用列名取数据\n",
    "print(type(df_obj['B'])) # <class 'pandas.core.series.Series'>\n",
    "print(\"-\"*50)\n",
    "print(df_obj.loc[0]) # 使用行索引取数据\n",
    "# print(df_obj[0]) # KeyError "
   ],
   "id": "348ce48406da648b",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A          B    C  D       E        F\n",
      "0  1 2019-09-26  1.0  1  Python  wangdao\n",
      "1  1 2019-09-26  1.0  2    Java  wangdao\n",
      "2  1 2019-09-26  1.0  3     C++  wangdao\n",
      "3  1 2019-09-26  1.0  4       C  wangdao\n",
      "--------------------------------------------------\n",
      "<class 'pandas.core.frame.DataFrame'>\n",
      "--------------------------------------------------\n",
      "0   2019-09-26\n",
      "1   2019-09-26\n",
      "2   2019-09-26\n",
      "3   2019-09-26\n",
      "Name: B, dtype: datetime64[s]\n",
      "<class 'pandas.core.series.Series'>\n",
      "--------------------------------------------------\n",
      "A                      1\n",
      "B    2019-09-26 00:00:00\n",
      "C                    1.0\n",
      "D                      1\n",
      "E                 Python\n",
      "F                wangdao\n",
      "Name: 0, dtype: object\n"
     ]
    }
   ],
   "execution_count": 65
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T16:28:04.888484Z",
     "start_time": "2025-01-07T16:28:04.879514Z"
    }
   },
   "cell_type": "code",
   "source": [
    "print(df_obj)\n",
    "print(\"-\" * 50)\n",
    "\n",
    "#增加列数据，列名是自定义的\n",
    "df_obj['G'] = df_obj[\"D\"]+4\n",
    "print(df_obj) \n",
    "print(\"-\" * 50)\n",
    "\n",
    "# 删除列\n",
    "del(df_obj[\"G\"])\n",
    "print(df_obj)"
   ],
   "id": "a9f29708ce5d02a0",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A          B    C  D       E        F\n",
      "0  1 2019-09-26  1.0  1  Python  wangdao\n",
      "1  1 2019-09-26  1.0  2    Java  wangdao\n",
      "2  1 2019-09-26  1.0  3     C++  wangdao\n",
      "3  1 2019-09-26  1.0  4       C  wangdao\n",
      "--------------------------------------------------\n",
      "   A          B    C  D       E        F  G\n",
      "0  1 2019-09-26  1.0  1  Python  wangdao  5\n",
      "1  1 2019-09-26  1.0  2    Java  wangdao  6\n",
      "2  1 2019-09-26  1.0  3     C++  wangdao  7\n",
      "3  1 2019-09-26  1.0  4       C  wangdao  8\n",
      "--------------------------------------------------\n",
      "   A          B    C  D       E        F\n",
      "0  1 2019-09-26  1.0  1  Python  wangdao\n",
      "1  1 2019-09-26  1.0  2    Java  wangdao\n",
      "2  1 2019-09-26  1.0  3     C++  wangdao\n",
      "3  1 2019-09-26  1.0  4       C  wangdao\n"
     ]
    }
   ],
   "execution_count": 63
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T16:16:25.934397Z",
     "start_time": "2025-01-07T16:16:25.928568Z"
    }
   },
   "cell_type": "code",
   "source": [
    "print(df_obj.index) # 行索引\n",
    "# Index([0, 1, 2, 3],dtype='int64')\n",
    "print(df_obj.columns) # 列索引\n",
    "# Index(['A', 'B', 'C', 'D', 'E', 'F'],dtype='object')\n",
    "print(df_obj.dtypes) # 每一列的数据类型"
   ],
   "id": "6797622d19628c9",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index([0, 1, 2, 3], dtype='int64')\n",
      "Index(['A', 'B', 'C', 'D', 'E', 'F'], dtype='object')\n",
      "A            int64\n",
      "B    datetime64[s]\n",
      "C          float32\n",
      "D            int32\n",
      "E           object\n",
      "F           object\n",
      "dtype: object\n"
     ]
    }
   ],
   "execution_count": 39
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-07T16:19:33.257495Z",
     "start_time": "2025-01-07T16:19:33.248493Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#pd.date_range()可以生成日期序列\n",
    "dates=pd.date_range('20190901',periods=6) # 生成6个日期\n",
    "\n",
    "# 第一个参数：插入数据\n",
    "# 第二个参数：行索引\n",
    "# 第三个参数：列索引\n",
    "df=pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('ABCD'))\n",
    "print(df)\n",
    "print(\"-\" * 50)\n",
    "print(df.index) # 行索引\n",
    "print(\"-\" * 50)\n",
    "print(df.columns)"
   ],
   "id": "6c4f2f055db1a2cd",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                   A         B         C         D\n",
      "2019-09-01  0.461502  1.875487  2.169285  0.421089\n",
      "2019-09-02  0.375415 -0.364281 -0.436482  0.251629\n",
      "2019-09-03 -1.992008 -0.383139  1.529862  0.126128\n",
      "2019-09-04  1.119211 -1.860418 -1.109165  0.664456\n",
      "2019-09-05 -1.772780  2.388247 -0.666092 -0.388308\n",
      "2019-09-06 -1.280079  0.879818  0.024664  2.471124\n",
      "--------------------------------------------------\n",
      "DatetimeIndex(['2019-09-01', '2019-09-02', '2019-09-03', '2019-09-04',\n",
      "               '2019-09-05', '2019-09-06'],\n",
      "              dtype='datetime64[ns]', freq='D')\n",
      "--------------------------------------------------\n",
      "Index(['A', 'B', 'C', 'D'], dtype='object')\n"
     ]
    }
   ],
   "execution_count": 44
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
